import fs from 'fs'
import { app } from 'electron'
import path from 'path'
import { updateMessage } from '../database/index'

export const writeFile = (fileName, arrayBuffer, id, key) => {
  return new Promise((resolve, reject) => {
    const buffer = Buffer.from(arrayBuffer)
    fs.writeFile(`${app.getPath('userData')}/file/${fileName}`, buffer, err => {
      if (err) {
        reject(err)
      } else {
        updateMessage(id, key, fileName)
        resolve('success')
      }
    })
  })
}

export const createFilePackage = () => {
  let FILE_PATH = path.join(app.getPath('userData'), '/file')
  // 检查文件是否存在于给定路径
  fs.access(FILE_PATH, fs.constants.F_OK, err => {
    if (err) {
      // 文件不存在
      fs.mkdir(FILE_PATH, err => {
        if (err) throw err
        console.log('文件夹创建成功')
      })
      return
    }
    // 文件存在
    console.log('文件存在')
  })
}
